# -*- coding: utf-8 -*-
"""
******************** 录音与播放 *********************
# @Time      : 2020/02/02
# @Author    : Dobot
*****************************************************
"""
from pyaudio import PyAudio, paInt16 
import numpy as np 
from datetime import datetime 
import wave
#定义类
class recorder:
    NUM_SAMPLES = 2000      #pyaudio内置缓冲大小
    SAMPLING_RATE = 16000   #取样频率   
    TIME_COUNT = 5          #录音时间，单位s
    Voice_Buff = []
    #初始化
    def __init__(self):
        self.Voice_Buff.clear()
                
    #录音函数
    def recorder(self,filename):
        pa = PyAudio() #实例化PyAudio对象
        #打开音频输入流，设置采样率等参数
        stream = pa.open(format=paInt16, 
                         channels=1, 
                         rate=self.SAMPLING_RATE, 
                         input=True,
                         frames_per_buffer=self.NUM_SAMPLES) 
        print("*"*10, "Start recording for 5 seconds!","*"*10)
        time_count = self.TIME_COUNT
        count = 0
        while count<time_count*10:
            # 一次性录音采样字节的大小
            string_audio_data = stream.read(self.NUM_SAMPLES)  
            self.Voice_Buff.append(string_audio_data)
            count +=1
            # 加逗号不换行输出
            print('.', end='') 
            if count%10 == 0:
                print("%ds\n"%int(count/10))        
        print("*"*10, "Stop recording!", "*"*10)
        stream.stop_stream()
        stream.close()
        pa.terminate()
        self.savewave(filename)
        
    #保存录音文件函数 
    def savewave(self,filename):
        wf = wave.open(filename, 'wb') 
        wf.setnchannels(1) 
        wf.setsampwidth(2) 
        wf.setframerate(self.SAMPLING_RATE) 
        wf.writeframes(b"".join(self.Voice_Buff)) 
        wf.close()
       
    def playwav(self,filename):
        print("*"*10, "Start playing!","*"*10)
        chunk=1024
        # 打开录制的音频文件
        wf = wave.open(filename, 'rb')  
        pa = PyAudio()            
        # 打开一个数据流对象，解码而成的帧将直接通过它播放出来，我们就能听到声音
        stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()),
                        channels=wf.getnchannels(),
                        rate=wf.getframerate(),
                        output=True)
        # 读取第一帧数据               
        data = wf.readframes(chunk)
        # 播放音频
        # 结束的标志为读到了空的帧
        while data != b'':
            # 将帧写入数据流对象中
            stream.write(data) 
            # 继续读取后面的帧               
            data = wf.readframes(chunk)       

        # 停止数据流
        stream.stop_stream() 
        stream.close()        
        pa.terminate()         
        print("*"*10, "Stop playing!","*"*10)
# 主程序入口      
if __name__ == "__main__":
    r = recorder()
    r.recorder("test.wav")
    r.playwav("test.wav")
